package com.example.wificollector;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

	private PositionListener positionListener;
	private WifiReceiver receiverWifi;
	TextView status;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		status = (TextView) findViewById(R.id.tvStatus);
	}

	public void onButtonClicked(View v) {
		receiverWifi = new WifiReceiver(this);
		positionListener = new PositionListener();
		
		
		TextView tvX = (TextView) findViewById(R.id.xValue);
		TextView tvY = (TextView) findViewById(R.id.yValue);
		TextView tvSample = (TextView) findViewById(R.id.samples);
		TextView tvInterval = (TextView) findViewById(R.id.interval);
        int x = Integer.parseInt(tvX.getText().toString());
        int y = Integer.parseInt(tvY.getText().toString());
        int sample = Integer.parseInt(tvSample.getText().toString());
        int interval = Integer.parseInt(tvInterval.getText().toString());
		receiverWifi.setPosition(x, y);
		receiverWifi.setCounter(sample);
		receiverWifi.setScanTimer(interval*1000);
		registerReceiver(positionListener, new IntentFilter("stopCollecting"));
		registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
		
		status.setText("Collecting started for pos: "+x+","+y+" Samples: "+ sample + " Interval "+interval);
	}

	private class PositionListener extends BroadcastReceiver {
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			status.setText("Collecting stopped");
			unregisterReceiver(receiverWifi);
			unregisterReceiver(positionListener);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
